package com.filetransfer.filedownloader.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import com.filetransfer.domain.FileInfoHolder;
import com.filetransfer.filemanager.util.FileUtil;

public class DownloadManager {

	private static Logger logger = Logger.getLogger(DownloadManager.class);
	private static FileDownloader downloader;

	static{
		DOMConfigurator.configure("./file-downloader-log.xml");
	}

	/**
	 *
	 * @param args
	 */
	public static void main(String[] args){

		if(!validateArgs(args)){
			System.exit(1);
		}


		printBanner();
		printCommands();
		BufferedReader reader = null;
		String command = null;

		try{
			reader = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("=>>");
			command = reader.readLine();
			/*
			 * Should start the server thread.
			 * The server thread should listen to the
			 * FileInfoRequest messages and serve back the list
			 * of files from the fileholder.
			 * Also start all the serving threads. lets do the
			 * request for file on the client end.
			 */
			while(!"exit".equals(command)){

				try{
					if("list-files-on-server".equals(command)){

						downloader.getFileInfoList();
						/*
						 * print the filelist
						 */
						System.out.println("-- Files Available for Download --:");
						FileUtil.listFiles(downloader.getFileList());

					}else if("show-downloads".equals(command)){
						//show the downloads from the session manager file, not the holder.
						downloader.getHolder().loadFileInfoList();
						FileUtil.listFilesOnDownloader(downloader.getHolder());
					}else if("download".equals(command)){
						System.out.print("Enter FileName =>>");
						command = reader.readLine();
						downloader.getFileInfoAndDownload(command);
					}else{
						System.out.println("invalid command!");
					}
					System.out.print("=>>");
					command = reader.readLine();
				}catch(Exception e){
					logger.error("Exception in the while in the mainController:" + e.getMessage());
					e.printStackTrace();
				}
			}

			/*
			 * Reached the end of the main thread. exit command issued. kill everything and exit gracefully.
			 */
			System.exit(0);

		}catch(Exception e){
			logger.error("Exception in the main - exiting!:" + e.getMessage());
			logger.error(e.getStackTrace().toString());
			System.out.println("Faced Exception in the main method, pls check log file. exiting program!");
			System.exit(1);
		}finally{
			try{
				if(reader != null){
					reader.close();
					reader = null;
				}
			}catch(Exception e){

			}
		}
	}



	/**
	 * Validates the command line arguments and sets the argsValid boolean and
	 * other properties appropriately.
	 */
	public static boolean validateArgs(String[] args){
		boolean validArgs = false;

		downloader = new FileDownloader();

		/*
		 * Argument validation.
		 * usage:
		 * java com.hac.proj.main.NodeManager -managerPort <value of manager port> -group <value of node multicast grp> -nodePort <node port>
		 *
		 * e.g.,
		 * java com.hac.proj.main.NodeManager -managerPort 7007 -group 234.0.0.1 -nodePort 4455
		 */

		try{
			if(args != null && args.length == 6){

				if("-serverHost".equals(args[0])){
					downloader.setServerPort(Integer.parseInt(args[1]));
					validArgs = true;
				}

				if("-receiverPort".equals(args[2])){
//					downloader.selfPort = Integer.parseInt(args[3]);
					validArgs = true;
				}

				if("-fileDir".equals(args[4])){
//					downloader.fileDir = args[5];
					validArgs &= validArgs;
				}

//				downloader.setHolder(new FileInfoHolder(downloader.getFileDir()),false);//the fileInfoHolder
				/*
				 * Start the FileServer Thread with the manager port.
				 */

			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("Exception in validateArgs!");
			logger.error(e.getStackTrace().toString());
			validArgs = false;

		}


		if(!validArgs){
			System.out.println("Usage of the File-Manager App:");
			System.out.println("=>> java com.filetransfer.filedownloader.controller.DownloadManager -serverPort <Port of the file server> -receiverPort <port to be used by this downloader>  -fileDir <Directory where the downloaded files can be stored> ");
			System.out.println("e.g.,\n=>> java com.filetransfer.filedownloader.controller.DownloadManager -serverPort 7007 -receiverPort 8001 -fileDir D:\\Temp\\download ");
		}


		return validArgs;
	}



	public static void printBanner(){
		System.out.println("****************************************************************");
		System.out.println("              File Download Manager - CommandLine Interface               ");
		System.out.println("****************************************************************");
	}



	/**
	 * Prints the Commands;
	 */
	public static void printCommands(){
		System.out.println("================================= Commands ========================================");
		System.out.println("list-files-on-server : requests the file server for a list of all the files that can be served. Displays the list.");
		System.out.println("show-downloads : Shows the completed, and paused downloads. ");
		System.out.println("download : starts downloading a file (resumes if the file is partially downloaded)."); //as of now do only single file at a time download option
		System.out.println("exit : Saves the download progress and exits.");
		System.out.println("===================================================================================");
	}

}
